package com.ishowcode.service.impl;

import com.ishowcode.beans.Email;
import com.ishowcode.service.ToEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.ThreadLocalRandom;
@Service
public class ToEmailServiceImpl implements ToEmailService {
    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String fromUser;
    @Override
    public String commonEmail(Email email) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(fromUser);
        mailMessage.setTo(email.getTos());
        String code = String.valueOf(ThreadLocalRandom.current().nextInt(100000,1000000));
        mailMessage.setText("您的验证码为: "+code+" 请在3分钟内使用哦!");
        String subject = code +"  is your code!";
        mailMessage.setSubject(subject);
        try {
            mailSender.send(mailMessage);
            return email.getTos()+"发送邮件成功";
        }catch (MailException e){
            e.printStackTrace();
            return email.getTos()+"发送邮件失败"+e.getMessage();
        }


    }
}
